package com.lwj.liwanjia.view.activity.dianpu;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.DianPuAdapter;
import com.lwj.liwanjia.adapter.KuaiDiAdapter;
import com.lwj.liwanjia.bean.CollectDianpuBean;
import com.lwj.liwanjia.bean.DianpuBean;
import com.lwj.liwanjia.bean.DpSpBean;
import com.lwj.liwanjia.bean.KuaidiBean;
import com.lwj.liwanjia.impl.CollectDianpuView;
import com.lwj.liwanjia.impl.DianpuView;
import com.lwj.liwanjia.impl.DpSpView;
import com.lwj.liwanjia.impl.KuaidiView;
import com.lwj.liwanjia.presenter.CollectDianpuPresenter;
import com.lwj.liwanjia.presenter.DianpuPresenter;
import com.lwj.liwanjia.presenter.DpSpPresenter;
import com.lwj.liwanjia.presenter.KuaidiPresenter;
import com.lwj.liwanjia.utils.PopUtils;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.view.activity.login.LoginActivity;
import com.lwj.liwanjia.view.activity.search.SearchActivity;
import com.lwj.liwanjia.view.activity.supermarket.ShangpinDetailActivity;
import com.superrecycleview.superlibrary.adapter.SuperBaseAdapter;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class DianpuActivity extends AppCompatActivity implements DianpuView, CollectDianpuView, DpSpView, KuaidiView {

    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.collapse_layout)
    CollapsingToolbarLayout collapseLayout;
    @BindView(R.id.shop_detail_apb)
    AppBarLayout shopDetailApb;
    @BindView(R.id.shop_detail_rlv)
    SuperRecyclerView shopDetailRlv;
    @BindView(R.id.iv_image)
    ImageView ivImage;
    @BindView(R.id.iv_fenlei)
    ImageView ivFenlei;
    @BindView(R.id.ed_sousuo)
    TextView edSousuo;
    Unbinder unbinder;
    @BindView(R.id.iv_collect)
    ImageView ivCollect;//收藏
    @BindView(R.id.iv_market)
    ImageView ivMarket;//店铺
    @BindView(R.id.tv_dianpupingfen)
    TextView tvDianpupingfen;//店铺评分
    @BindView(R.id.tv_fuwu_pingfen)
    TextView tvFuwuPingfen;//服务评分
    @BindView(R.id.tv_wuliu_pingfen)
    TextView tvWuliuPingfen;//物流评分
    @BindView(R.id.tv_market_name)
    TextView marketName;//店铺名字
    @BindView(R.id.tv_guanzhu_number)
    TextView guanzhuNumber;//关注人数
    @BindView(R.id.shop_coor)
    CoordinatorLayout coordinatorLayout;

    private LayoutInflater inflater;
    private Window window;
    private List<DpSpBean.DataBean> list = new ArrayList<>();
    private DianPuAdapter adapter;
    private ViewHolder holder;
    private TextView tvShangpin;//大类
    private TextView tvTab;//小类
    private String mPrice;//价格是从高到低还是从低到高
    private PopupWindow popupWindow;
    private KuaiDiViewHolder kuaiDiHolder;//选择快递方式
    private int selection = 0;//选中快递的位置
    private List<String> kdList = new ArrayList<>();//快递方式
    private KuaiDiAdapter kuaiDiAdapter;
    private DianpuPresenter dianpuPresenter;
    private CollectDianpuPresenter collectPresenter;
    private String token;
    private int shopInfoId;
    private DianpuBean.DataBean data;
    private DpSpPresenter dpSpPresenter;
    private KuaidiPresenter kuaidiPresenter;
    private String isWebShop;
    private Map<String, Object> map = new HashMap<>();
    private int isFirst = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dianpu);
        setStableTransparent(0);
        unbinder = ButterKnife.bind(this);
        inflater = LayoutInflater.from(this);
        initView();
        initData();
        listener();
    }

    private void listener() {
        //商品进入详情
        adapter.setOnItemClickListener(new SuperBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object item, int position) {
                Intent intent = new Intent(DianpuActivity.this, ShangpinDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("shopGoodsCode", list.get(position).getCommodityCode());
                bundle.putString("commodityType", list.get(position).getCommodityType());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        //滑动监听
        shopDetailApb.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset < -(ivImage.getHeight() - 256)) {
                    setStableTransparent(1);
                } else {
                    setStableTransparent(0);
                }
            }
        });
        //店铺信息
        ivMarket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DianpuActivity.this, DianpuInforActivity.class);
                intent.putExtra("info", data);
                startActivity(intent);
            }
        });
        //全部商品
        holder.tvAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setColor(holder.tvAll, tvTab);
            }
        });
        //热卖商品
        holder.tvRemai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setColor(holder.tvRemai, tvTab);
            }
        });
        //最新上架
        holder.tvNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setColor(holder.tvNew, tvTab);
            }
        });
        //活动促销
        holder.tvCuxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setColor(holder.tvCuxiao, tvTab);
            }
        });
        //商品分类
        holder.tvFenlei.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(DianpuActivity.this, ShopClassifyActivity.class);
//                startActivity(intent);
                Toast.makeText(DianpuActivity.this, "暂不支持分类", Toast.LENGTH_SHORT).show();
            }
        });
        //销量
        holder.tvSales.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selection = 0;
                setColor(tvShangpin, holder.tvSales);
            }
        });
        //价格
        holder.tvPrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFirst == 0) {
                    mPrice = "从低到高";
                    holder.heightPrice.setImageResource(R.mipmap.gao);
                    holder.lowerPrice.setImageResource(R.mipmap.di);
                    selection = 0;
                    isFirst = 1;
                    setColor(tvShangpin, holder.tvPrice);
                } else if (isFirst == 1) {
                    holder.heightPrice.setImageResource(R.mipmap.gao_1);
                    holder.lowerPrice.setImageResource(R.mipmap.di_1);
                    mPrice = "从高到低";
                    selection = 0;
                    isFirst = 0;
                    setColor(tvShangpin, holder.tvPrice);
                }
            }
        });

        //好评度
        holder.tvHaopingdu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selection = 0;
                setColor(tvShangpin, holder.tvHaopingdu);
            }
        });
        //筛选
        holder.tvShaixuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setColor(tvShangpin, holder.tvShaixuan);
                kuaidiPresenter.getKuaidi();
            }
        });
    }

    private void initView() {
        shopInfoId = getIntent().getIntExtra("shopInfoId", 0);
        GridLayoutManager manager = new GridLayoutManager(this, 2);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        shopDetailRlv.setLayoutManager(manager);
        shopDetailRlv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.right = getResources().getDimensionPixelOffset(R.dimen.x10);
                outRect.bottom = getResources().getDimensionPixelOffset(R.dimen.x10);
                //使得添加的headView能够铺满整个屏幕的宽
                if (parent.getChildAdapterPosition(view) == 0 || parent.getChildAdapterPosition(view) == 1) {
                    outRect.right = 0;
                    outRect.bottom = 0;
                }

                if (parent.getChildAdapterPosition(view) % 2 == 0) {
                    outRect.left = getResources().getDimensionPixelOffset(R.dimen.x10);
                }
            }
        });
        shopDetailRlv.setRefreshEnabled(false);
        shopDetailRlv.setLoadMoreEnabled(false);
        adapter = new DianPuAdapter(this, list);
        addView();
        shopDetailRlv.setAdapter(adapter);
        tvShangpin = holder.tvAll;
        tvTab = holder.tvSales;
        token = SpfUtils.getSpfUtils(this).getToken();
        dianpuPresenter = new DianpuPresenter(this);
        collectPresenter = new CollectDianpuPresenter(this);
        dpSpPresenter = new DpSpPresenter(this);
        kuaidiPresenter = new KuaidiPresenter(this);
    }

    private void addView() {
        //添加导航标签
        View view = inflater.inflate(R.layout.dianpu_head, null);
        holder = new ViewHolder(view);
        adapter.addHeaderView(view);
    }

    private void initData() {
        if (shopInfoId != 0) {
            dianpuPresenter.getDianpuData(token, shopInfoId);
        }
    }

    //修改状态栏
    public void setStableTransparent(int state) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            if (state == 0) {
                window.setStatusBarColor(0x00000000);
            } else {
                window.setStatusBarColor(getResources().getColor(R.color.colorEC921A));
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        if (dianpuPresenter != null) {
            dianpuPresenter = null;
        }
        if (collectPresenter != null) {
            collectPresenter = null;
        }
        if (kuaidiPresenter != null) {
            kuaidiPresenter = null;
        }
        if (dpSpPresenter != null) {
            dpSpPresenter = null;
        }

    }


    @OnClick({R.id.iv_collect, R.id.iv_market, R.id.tv_back, R.id.ed_sousuo, R.id.iv_fenlei})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_collect://收藏
                collectPresenter.collectDianpu(token, shopInfoId);
                break;
            case R.id.iv_market://头像
                break;
            case R.id.tv_back://返回
                finish();
                break;
            case R.id.ed_sousuo://搜索
                Intent intent = new Intent(DianpuActivity.this, SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_fenlei://分类
                PopUtils.getInstance().showPopupWindow(DianpuActivity.this, (ImageView) view);
                break;
        }
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(this, "数据加载失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getKuaidi(KuaidiBean kuaidiBean) {
        List<String> data = kuaidiBean.getData();
        if (data.size() > 0) {
            kdList.clear();
            kdList.addAll(data);
            showPopupWindow();
        }
    }

    @Override
    public void getDpSpData(DpSpBean dpSpBean) {
        if (dpSpBean.getState() == 0) {
            Toast.makeText(this, "访问失败", Toast.LENGTH_SHORT).show();
        } else if (dpSpBean.getState() == 1) {
            list.clear();
            list.addAll(dpSpBean.getData());
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void collectDianpu(CollectDianpuBean collectDianpuBean) {
        if (collectDianpuBean.getState() == 1) {
            String s = guanzhuNumber.getText().toString().split("人")[0];
            if (collectDianpuBean.isData()) {
                ivCollect.setImageResource(R.mipmap.shoucang_xuanzhong);
                guanzhuNumber.setText((Integer.parseInt(s) + 1) + "人关注");
            } else {
                ivCollect.setImageResource(R.mipmap.shoucang_weixuanzhong);
                guanzhuNumber.setText((Integer.parseInt(s) - 1) + "人关注");
            }
        } else {
            Toast.makeText(this, "收藏失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getDianpuData(DianpuBean dianpuBean) {
        if (dianpuBean.getState() == 0) {
            Toast.makeText(this, "访问失败", Toast.LENGTH_SHORT).show();
        } else if (dianpuBean.getState() == 1) {
            coordinatorLayout.setVisibility(View.VISIBLE);
            data = dianpuBean.getData();
            if (data.getCollect() == 1) {
                ivCollect.setImageResource(R.mipmap.shoucang_xuanzhong);
            } else {
                ivCollect.setImageResource(R.mipmap.shoucang_weixuanzhong);
            }
            tvDianpupingfen.setText("店铺评分" + data.getShopGrade() + "分");//店铺评分
            tvFuwuPingfen.setText("服务评分" + data.getServeGrade() + "分");//服务评分
            tvWuliuPingfen.setText("物流评分" + data.getLogisticsGrade() + "分");//物流评分
            marketName.setText(data.getShopName());//店铺名字
            Glide.with(this).load(data.getShopImage()).placeholder(R.mipmap.shop_image_1).into(ivMarket);
            Glide.with(this).load(data.getBackImg()).placeholder(R.mipmap.shop_image).into(ivImage);
            guanzhuNumber.setText(data.getCollectNum() + "人关注");
            isWebShop = data.getIsWebShop();
            getMaps();
            dpSpPresenter.getDpSpData(map);
        }
    }

    public void getMaps() {
        map.put("token", token);
        map.put("shopInfoId", shopInfoId);
        map.put("oneType", tvShangpin.getText().toString());
        map.put("twoType", tvTab.getText().toString());
        map.put("isWebShop", isWebShop);
    }

    static class ViewHolder {
        @BindView(R.id.layout1)
        LinearLayout layout1;
        @BindView(R.id.tv_sales)
        TextView tvSales;//销量
        @BindView(R.id.tv_price)
        TextView tvPrice;//价格
        @BindView(R.id.height_price)
        ImageView heightPrice;//高价格
        @BindView(R.id.lower_price)
        ImageView lowerPrice;//低价格
        @BindView(R.id.relative_price)
        FrameLayout relativePrice;
        @BindView(R.id.tv_haopingdu)
        TextView tvHaopingdu;//好评度
        @BindView(R.id.tv_shaixuan)
        TextView tvShaixuan;//筛选
        @BindView(R.id.shop_tab)
        LinearLayout shopTab;
        @BindView(R.id.tv_all)
        TextView tvAll;//全部商品
        @BindView(R.id.tv_remai)
        TextView tvRemai;//热卖商品
        @BindView(R.id.tv_new)
        TextView tvNew;//最新上架
        @BindView(R.id.tv_cuxiao)
        TextView tvCuxiao;//活动促销
        @BindView(R.id.tv_fenlei)
        TextView tvFenlei;//分类


        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    /**
     * 选项处理
     *
     * @param tv1 全部商品 大类
     * @param tv2 销量 小类
     */
    private void setColor(TextView tv1, TextView tv2) {
        if (tvShangpin != tv1) {
            tvShangpin.setBackgroundColor(Color.WHITE);
            tvShangpin.setTextColor(getResources().getColor(R.color.color3B3B3B));
            tv1.setBackgroundColor(getResources().getColor(R.color.colorCECECE));
            tv1.setTextColor(Color.WHITE);
            tvShangpin = tv1;
        }
        if (tvTab != tv2) {
            tvTab.setTextColor(getResources().getColor(R.color.colorC4C4C4));
            tv2.setTextColor(getResources().getColor(R.color.colorEC921A));
            tvTab = tv2;
        }
        if (tvTab != holder.tvPrice) {//如果没有选中价格
            holder.heightPrice.setImageResource(R.mipmap.gao_1);
            holder.lowerPrice.setImageResource(R.mipmap.di);
            isFirst = 0;
        }
        if (!tvTab.getText().toString().equals("筛选")) {
            if (tvTab.getText().toString().equals("价格")) {
                map.put("twoType", mPrice);
            } else {
                map.put("twoType", tvTab.getText().toString());
            }
            map.put("oneType", tvShangpin.getText().toString());
            dpSpPresenter.getDpSpData(map);
        }
    }


    //弹出筛选popupWindow
    private void showPopupWindow() {
        final View popview = LayoutInflater.from(this).inflate(R.layout.popupwindow_layout, null);
        popupWindow = new PopupWindow(popview, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        //设置弹出窗体不可点击
        popupWindow.setFocusable(true);
        //实例化一个ColorDrawable,点击窗体外部区域时消失
        ColorDrawable cd = new ColorDrawable();
        popupWindow.setBackgroundDrawable(cd);
        popupWindow.setOutsideTouchable(true);
        //设置动画
        //   popupWindow.setAnimationStyle(R.style.PopupAnimation);
        //弹出位置
        popupWindow.showAsDropDown(holder.tvShaixuan);
        kuaiDiHolder = new KuaiDiViewHolder(popview);
        kuaiDiAdapter = new KuaiDiAdapter(this, kdList);
        kuaiDiAdapter.setCheckPosition(selection);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        kuaiDiHolder.rlvKuaidi.setLayoutManager(manager);
        kuaiDiHolder.rlvKuaidi.setRefreshEnabled(false);
        kuaiDiHolder.rlvKuaidi.setLoadMoreEnabled(false);
        kuaiDiHolder.rlvKuaidi.setAdapter(kuaiDiAdapter);
        //快递方式
        kuaiDiAdapter.setOnItemClickListener(new SuperBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object item, int position) {
                selection = position;
                kuaiDiAdapter.setCheckPosition(selection);
                kuaiDiAdapter.notifyDataSetChanged();
                popupWindow.dismiss();
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //在这里调用接口
                map.put("twoType", kdList.get(selection));
                map.put("oneType", tvShangpin.getText().toString());
                dpSpPresenter.getDpSpData(map);
            }
        });
    }


    /**
     * 快递
     */
    static class KuaiDiViewHolder {
        @BindView(R.id.rlv_kuaidi)
        SuperRecyclerView rlvKuaidi;

        KuaiDiViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
